package com.example.client.controller.comment;

import com.example.commentservice.service.CommentService;
import com.example.commonapi.pojo.Comment;
import com.example.commonapi.pojo.User;
import com.example.userservice.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
public class CommentRestController {
    private static final Log logger = LogFactory.getLog(CommentRestController.class);

    @Autowired
    private ObjectMapper objectMapper;
    @Reference(version = "${demo.service.version}")
    private CommentService commentService;
    @Reference(version = "${demo.service.version}")
    private UserService userService;

    @PostMapping("/comment/update")
    public String commentUpdate(@RequestBody Comment comment) {
        commentService.updateComment(comment);
        return "1";
    }

    @PostMapping("/comment/delete")
    public String commentDelete(@RequestBody Comment comment) {
        commentService.deleteComment(comment.getId());
        return "1";
    }

    @PostMapping("/comment/get")
    public String getAllComment(String id) throws JsonProcessingException {
        return objectMapper.writeValueAsString(commentService.getCommentByTopicId(Integer.valueOf(id)));
    }

    @PostMapping("/comment/add")
    public String commentAdd(@RequestBody Comment comment, HttpServletRequest request) {
        int userId = ((User) request.getSession().getAttribute("user")).getId();
        comment.setUserId(userId);

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        comment.setTime(formatter.format(new Date()));

        commentService.addComment(comment);

        return "success";
    }
}
